/**
 * Copyright 2011 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.codelab;

import java.io.IOException;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.GeoPt; 

import java.util.Date;


/**
 * This class defines the methods for basic operations of create, update & retrieve
 * for order entity
 *  
 * @author
 *
 */
public class Message {

	/**
	 * Create a message entity.
	 * The message has many properties. All needs to be added in a single transaction.
	 * 
	 * @param userName
	 *          : customer placing the order
	 * @param type
	 *          : type of message (regular, superuser, reply)
	 * @param header
	 *          : header/subject of message
	 * @param text
	 *          : text of message
	 * @param geo
	 *          : geo location
	 * @throws IOException 
	 */
  public static void createMessage(String userName, String text,
			String geo, int likes) throws IOException {
    Transaction txn = Util.getDatastoreServiceInstance().beginTransaction();
    try {
  //    Entity user = User.getSingleUser(userName);
  //    Key userkey = user.getKey();
      
    	Entity message = new Entity("Message");

    	message.setProperty("userName", 	userName);
    	message.setProperty("type",			"common");
    	message.setProperty("header",		"header");
    	message.setProperty("text",			text);
    	message.setProperty("blobLink", 	"blobLink");
    	message.setProperty("likes", 		0);
    	message.setProperty("likesLnk",		"likesLinks");
    	
    	Date dateComposed = new Date();
    	// Expiration date is set to 5 min since creation
    	Date dateExpires = new Date(dateComposed.getTime()+5*1000*60);
    	message.setProperty("dateComp",		dateComposed);
    	message.setProperty("dateUpd",		dateComposed);
    	message.setProperty("dateExp",		dateExpires);
    	
    	message.setProperty("replies",		"");
    	message.setProperty("theme",		"theme");
    	
    	GeoPt geo1 = new GeoPt(1, 1);
    	message.setProperty("geo", 			geo1);
      
    	Util.getDatastoreServiceInstance().put(message);
    	txn.commit();
    } finally {
      if (txn.isActive()) {
    	// Error in createMsg transaction
        txn.rollback();
      }
    }
  }
  
	/**
	 * Updates message likes array.
	 * 
	 * @param key
	 *          : key of the message to be liked
	 * @param likes
	 *          : like change array
	 * @throws IOException 
	 */
  
  public static void likeMessage(Key key, int likes) throws IOException {
  Transaction txn = Util.getDatastoreServiceInstance().beginTransaction();
  try {
    Entity message = Util.findEntity(key);
    long likesnum = (Long)message.getProperty("likes");
    message.setProperty("likes", likesnum+1);
    Util.getDatastoreServiceInstance().put(message);
    txn.commit();
  } finally {
    if (txn.isActive()) {
    	// Error in likeMsg transaction
      txn.rollback();
    }
  }
}

	/**
	 * Get all the messages
	 * 
	 * @return : list of all messages
	 */
  public static Iterable<Entity> getAllMessage() {
    Iterable<Entity> entities = Util.listEntities("Message", null, null);
    return entities;
  }

	/**
	 * Get the list of message for a specific customer
	 * 
	 * @param userName
	 * @return the list of messages as iterable
	 */
  public static Iterable<Entity> getAllMessagesForUser(String userName) {
    Key userKey = KeyFactory.createKey("User", userName);
    return Util.listChildren("Message", userKey);
  }
  
  public static Iterable<Entity> getAllMessages() {
	    return Util.listAll("Message");
  }
  
}
